package top.code.attend.service;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.code.attend.dao.AttendMapper;
import top.code.attend.entity.Attend;
import top.code.attend.viewObject.QueryCondition;
import top.code.common.utils.DateUtils;
import top.code.common.utils.PageQueryBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by setsun on 2017/9/25.
 */
@Service("attendServiceImpl")
public class AttendServiceImpl implements AttendService{
    /**
    *@Author benson {www.honey520.com}
    *@Date 2017/9/26 9:16
    *@Description 判定上下午 中午十二点
    */
    private static final int NOON_MUNITE = 12;
    private static final int NOON_HOUR   = 00;
    /**
     * 早晚上班时间判定
     */
    private static final int MORNING_HOUR = 9;
    private static final int MORNING_MINUTE = 30;
    private static final int EVENING_HOUR = 18;
    private static final int EVENING_MINUTE = 30;

    /**
     * 缺勤一整天
     */
    private static final Integer ABSENCE_DAY =480 ;
    /**
     * 考勤异常状态
     */
    private static final Byte ATTEND_STATUS_ABNORMAL = 2;
    private static final Byte ATTEND_STATUS_NORMAL = 1;

    private Log log  = LogFactory.getLog(AttendServiceImpl.class);

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Autowired
    private AttendMapper attendMapper;

    /**
    *@Author benson {www.honey520.com}
    *@Date 2017/9/26 19:22
    *@Description 打卡记录 十二点以前是上午上班时间 十二点以后,下午时间  如果不存在
     *  就判断记录是不是在九点半之前 就当作正常数据直接加入数据库
     * 如果在这之后就将Status设置为异常 并且将时间差存进去
     * 如果九点半之后,就直接异常存入数据库
    */
    @Override
    public void signAttend(Attend attend) {
        try {
            Date today = new Date();    //当前时间
            attend.setAttendDate(today);    //时间
            attend.setAttendWeek((byte) DateUtils.getTodayWeek());  //星期数
            //查询当天,有没有打卡记录
            Attend todayRecord = attendMapper.selectTodaySignRecord(attend.getUserId());
            Date noon = DateUtils.getDate(NOON_HOUR,NOON_MUNITE);   //当前打卡时间
            Date morningAttend = DateUtils.getDate(MORNING_HOUR,MORNING_MINUTE);    // 早上打卡时间
            //打卡记录不存在
            if(todayRecord == null){
                //中午十二点之前打卡算早晨  9.30直接异常迟到
                if(today.compareTo(noon)<=0) {
                    //十二点之前
                    attend.setAttendMorning(today);
                    //是否晚于九点三十
                    if(today.compareTo(noon)>0){    //当前时间是否在打卡时间之后
                        attend.setAttendStatus(ATTEND_STATUS_ABNORMAL); //2
                        attend.setAbsence(DateUtils.getMunite(morningAttend,today));
                    }
                }else{
                    attend.setAttendEvening(today);
                }
                attendMapper.insertSelective(attend);   //插入到数据库
            }else{
                //中午十二点之前打卡
                if(today.compareTo(noon)<=0){
                    return;
                }else {
                    //晚上打卡
                    todayRecord.setAttendEvening(today);
                    //获取下午打卡时间
                    Date eveningAttend = DateUtils.getDate(EVENING_HOUR,EVENING_MINUTE);
                    if (today.compareTo(eveningAttend)<0){  //小于0 在这之前
                        todayRecord.setAttendStatus(ATTEND_STATUS_ABNORMAL);
                        todayRecord.setAbsence(DateUtils.getMunite(today,eveningAttend));   //当前时间和晚上打卡时间
                    }else{
                        todayRecord.setAttendStatus(ATTEND_STATUS_NORMAL);
                        todayRecord.setAbsence(0);
                    }
                    attendMapper.updateByPrimaryKeySelective(todayRecord);   //更新时间,插入进去
                }
            }
        }catch (Exception e){
            log.error("用户签到异常",e);
            throw e;
        }
    }
    /**
    *@Author benson {www.honey520.com}
    *@Date 2017/9/26 18:53
    *@Description 查询数据分页显示
    */
    @Override
    public PageQueryBean listAttend(QueryCondition condition) {
       //根据条件查询count记录数目
        int count = attendMapper.countByCondition(condition);
        PageQueryBean pageResult = new PageQueryBean();
        if (count>0){
            pageResult.setTotalRows(count);
            pageResult.setCurrentPage(condition.getCurrentPage());  //当前点击页数
            pageResult.setPageSize(condition.getPageSize());    //总页数
            //如果有记录才去查询分页数据(selectAttendPage) ,没有相关记录,就不去查看分页数据
            List<Attend> attendlist = attendMapper.selectAttendPage(condition);
            pageResult.setItems(attendlist);    //把后台查询到数据传到view

        }
        return pageResult;
    }

    /**
    *@Author benson {www.honey520.com}
    *@Date 2017/9/26 19:23
    *@Description
    */

    @Override
    @Transactional
    public void checkAttend() {
        //查询缺勤用户ID 插入打卡记录 并且设置为异常
        List<Long> userIdList = attendMapper.selectTOdayAbsence();
        if (CollectionUtils.isNotEmpty(userIdList)){
            List<Attend> attendList = new ArrayList<>();
            for (Long userId:userIdList) {
                Attend attend = new Attend();
                attend.setUserId(userId);
                attend.setAttendDate(new Date());
                attend.setAttendWeek((byte) DateUtils.getTodayWeek());
                attend.setAbsence(ABSENCE_DAY);
                attend.setAttendStatus(ATTEND_STATUS_ABNORMAL);
                attendList.add(attend);
            }
            attendMapper.batchInsert(attendList);   //批量插入
        }
        // 检查晚打卡 将下班未打卡记录设置为异常
        List<Attend> absenceList = attendMapper.selectTodayEveningAbsence();
        if(CollectionUtils.isNotEmpty(absenceList)){
            for(Attend attend : absenceList){
                attend.setAbsence(ABSENCE_DAY);
                attend.setAttendStatus(ATTEND_STATUS_ABNORMAL);
                attendMapper.updateByPrimaryKeySelective(attend);
            }
        }
    }


}
